package com.acme.task1;

public class Calculator {

	private static final String ERR_PARSE_NUMBER   = "'%s' is not a number";
	private static final String ERR_ARGS_COUNT     = "3 arguments required";
	private static final String ERR_WRONG_OPERATOR = "'%s' is not a vaild operator";
	private static final String ERR_TEMPLATE       = "Error: %s%n";

	public static void main(String[] args) {
		try {
			double result = performCalculation(args);
			System.out.println(result);
		} catch (IllegalArgumentException e) {
			System.out.printf(ERR_TEMPLATE, e.getMessage());
			printHelp();
		}
	}
	
	private static double performCalculation(String[] args) {
		if (args.length != 3) throw new IllegalArgumentException(ERR_ARGS_COUNT);

		double lhs = parseDouble(args[0]);
		double rhs = parseDouble(args[2]);
		double result;

		String operator = args[1];

		switch (operator) {
			case "+":
				result = lhs + rhs;
				break;
			case "-":
				result = lhs - rhs;
				break;
			case "*":
				result = lhs * rhs;
				break;
			case "/":
				result = lhs / rhs;
				break;
			default:
				String msg = String.format(ERR_WRONG_OPERATOR, operator);
				throw new IllegalArgumentException(msg);
		}

		return result;
	}
	
	private static double parseDouble(String str) {
		try {
			return Double.parseDouble(str);
		} catch (Exception e) {
			String msg = String.format(ERR_PARSE_NUMBER, str);
			throw new IllegalArgumentException(msg, e);
		}
	}
	
	private static void printHelp() {
		System.out.println("Usage:   java Calc <operand_1> <operator> <operand_2>");
		System.out.println("Example: java Calc 2.5 + 7.5");
	}

}
